package leetcode.f1t100;

public class Q24_SwapNodesInPairs {

    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, null))));
        head = new Q24_SwapNodesInPairs().swapPairs(head);
        while(head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }


    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode zero= new ListNode();
        zero.next = head;
        ListNode cur = head,pre = zero,next=cur.next;
        while (cur != null && cur.next != null){
            next = cur.next;
            pre.next = cur.next;
            cur.next = next.next;
            next.next = cur;
            pre = cur;
            cur = cur.next;

        }
        return zero.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
